import { reqCartList, reqAddcart, reqchangeChecked } from "@/api/shopcart";
const state = {
  cartList: [],
};
const actions = {
  async getcartlist({ state, commit, dispatch }) {
    let res = await reqCartList();
    if (res.code === 200) {
      commit("GETCARTLIST", res.data);
    }
  },
  async addOneFun({ state, commit, dispatch }, { skuId, skuNum }) {
    let res = await reqAddcart({ skuId, skuNum });
    if (res.code == 200) {
      return "ok";
    } else {
      return Promise.reject();
    }
  },
  async minusOneFun({ state, commit, dispatch }, { skuId, skuNum }) {
    let res = await reqAddcart({ skuId, skuNum });
    if (res.code === 200) {
      return "ok";
    } else {
      return Promise.reject();
    }
  },
  async changeCheckedFun({ state, commit, dispatch }, { skuId, isChecked }) {
    let res = await reqchangeChecked({ skuId, isChecked });
    if (res.code == 200) {
      return "ok";
    } else {
      return Promise.reject();
    }
  },
  allChangeFun({ state, commit, dispatch }, isChecked) {
    let arr = [];
    state.cartList[0].cartInfoList.forEach((item) => {
      let res = dispatch("changeCheckedFun", { skuId: item.skuId, isChecked });
      arr.push(res);
    });
    return Promise.all(arr);
  },
};
const mutations = {
  GETCARTLIST(state, data) {
    state.cartList = data;
  },
};
const getters = {
  info(state) {
    return state.cartList[0] || {};
  },
  good(state, getters) {
    return getters.info.cartInfoList || [];
  },
};

export default {
  namespaced: "shopCart",
  state,
  actions,
  mutations,
  getters,
};
